class MyPromise {
    constructor(executor) {
        this.status = 'pending';
        this.value = undefined;
        this.reason = undefined;

        this.onFulfilledCallbacks = [];
        this.onRejectedCallbacks = [];

        const resolve = val => {
            if (this.status === 'pending') {
                this.status = 'fulfilled';
                this.value = val;
                this.onFulfilledCallbacks.forEach(cb => cb());
            }
        }
        const reject = reason => {
            if (this.status === 'pending') {
                this.status = 'rejected';
                this.reason = reason;
                this.onRejectedCallbacks.forEach(cb => cb());
            }
        }
        try {
            executor(resolve, reject);
        } catch (error) {
            reject(error);
        }
    }
    then (onFulfilled, onRejected) {
        return new MyPromise((resolve, reject) => {
            if (this.status === 'fulfilled') {
                setTimeout(() => {
                    onFulfilled(this.value);
                })

            }
            if (this.status === 'rejected') {
                onRejected(this.reason)
            }
            if (this.status === 'pending') {
                this.onFulfilledCallbacks.push(() => {
                    onFulfilled(this.value);
                })
                this.onRejectedCallbacks.push(() => {
                    onRejected(this.reason)
                })
            }
        })
    }
    static resolve(value){
        return new MyPromise((resolve) => resolve(value))
    }
    static all (promises) {
        return new MyPromise((resolve, reject) => {
            let result = [];

            promises.forEach((promises) => {
                MyPromise.resolve(promises).then(val => {
                    result.push(val);
                    if (result.length === promises.length) {
                        resolve(result);
                    }
                }, reject)
            })
        })
    }
}